//
//  GizToken.m
//  PhnixHome
//
//  Created by Levy Xu on 2018/3/3.
//  Copyright © 2018年 Levy Xu. All rights reserved.
//

#import "GizToken.h"
#import "GizConstant.h"

@implementation GizToken

+(GizToken *)tokenThisUser {
    NSString *filePath = [DOC_DIR stringByAppendingFormat:@"/tokens/%@", APP_DELEGATE.token.user_id];
    if ([FM fileExistsAtPath:filePath]) {
        GizToken *token = [GizToken mj_objectWithFile:filePath];
        if (token && token.uid && token.token && token.expire_at > [[NSDate date] timeIntervalSince1970]) {
            return token;
        }
    }
    return nil;
}

+(void)loginAnonymous:(void (^)(GizToken *token))block {
    GizToken *token = [GizToken tokenThisUser];
    if (token) {
        LOG(@"token %@",token.mj_keyValues);
        !block ?: block(token);
    } else {
        NSDictionary *paras = @{ @"phone_id": APP_DELEGATE.token.user_id };
        LOG(@"paras %@",paras);
        [[GizConstant gizHTTPManager] POST:kUrlCreatUser parameters:paras progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            GizToken *result = [GizToken mj_objectWithKeyValues:responseObject];
            [result save];
            LOG(@"token %@", result.mj_keyValues);
            !block ?: block(result);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            LOG(@"error %@", error.description);
            !block ?: block(nil);
        }];
    }
}

-(void)save {
    NSString *tokenPath = [DOC_DIR stringByAppendingPathComponent:@"tokens"];
    [FM createDirectoryAtPath:tokenPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString *filePath = [tokenPath stringByAppendingPathComponent:APP_DELEGATE.token.user_id];
    BOOL result = [self.mj_keyValues writeToFile:filePath atomically:YES];
    if (result) {
        LOG(@"giz token save success");
    } else {
        LOG(@"giz token save failed");
    }
}

@end
